<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Observers;

use App\Models\UserBankCard;

class UserBankCardObserver
{
    /**
     * Handle the UserBankCard "created" event.
     */
    public function created(UserBankCard $userBankCard)
    {
    }

    /**
     * Handle the UserBankCard "updated" event.
     */
    public function updated(UserBankCard $userBankCard)
    {
    }

    public function deleted(UserBankCard $userBankCard)
    {
        if ($userBankCard->is_default == 1) {
            // 自动将用户最新地址设为默认
            $newDefault = UserBankCard::query()
                ->where('user_id', $userBankCard->user_id)
                ->latest()
                ->first();
            if ($newDefault) {
                $newDefault->update(['is_default' => 1]);
            }
        }
    }

    /**
     * Handle the UserBankCard "restored" event.
     */
    public function restored(UserBankCard $userBankCard)
    {
    }

    /**
     * Handle the UserBankCard "force deleted" event.
     */
    public function forceDeleted(UserBankCard $userBankCard)
    {
    }

    public function saving(UserBankCard $userBankCard)
    {
        if ($userBankCard->is_default == 1) {
            UserBankCard::query()->where('user_id', $userBankCard->user_id)
                ->where('id', '!=', $userBankCard->id) // 排除自身（如果是更新操作）
                ->update(['is_default' => 0]);
        }
        if ($userBankCard->getOriginal('is_default') == 1 && $userBankCard->is_default == 0) {
            $newDefault = UserBankCard::query()
                ->where('user_id', $userBankCard->user_id)
                ->where('id', '<>', $userBankCard->id)
                ->latest()
                ->first();
            if ($newDefault) {
                $newDefault->update(['is_default' => 1]);
            }
        }
    }
}
